﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Drawing.Printing;
using System.Diagnostics;

namespace Mentor_Database
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.booksTableAdapter.Fill(this.bookDataSet.books);
        }

        private void helpToolStripButton_Click(object sender, EventArgs e)
        {
            AboutBox1 a = new AboutBox1();
            a.ShowDialog();
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            Stream xmlStream = null;
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            ofd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            ofd.FilterIndex = 1 ;
            ofd.RestoreDirectory = true ;

            if(ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((xmlStream = ofd.OpenFile()) != null)
                    {
                        DataSet temp = new DataSet();
                        temp.ReadXml(xmlStream, XmlReadMode.Auto);
                        this.bookDataSet.Merge(temp, true, MissingSchemaAction.Ignore);
                        this.booksTableAdapter.Update(this.bookDataSet);
                        xmlStream.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            Stream xmlStream;
            sfd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            sfd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            sfd.FilterIndex = 1;
            sfd.RestoreDirectory = true;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((xmlStream = sfd.OpenFile()) != null)
                    {
                        this.bookDataSet.WriteXml(xmlStream, XmlWriteMode.WriteSchema);
                        xmlStream.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }
        
        private void booksDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show(e.Exception.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if ((e.Exception) is ConstraintException)
            {
                DataGridView view = (DataGridView)sender;
                view.Rows[e.RowIndex].ErrorText = "an error";
                view.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "an error";

                e.ThrowException = false;
            }
        }

        private void toolStripSearchBox_TextChanged(object sender, EventArgs e)
        {
            String s;
            ToolStripTextBox tstb = (ToolStripTextBox)sender;
            s = "%" + tstb.Text + "%";
            this.bookDataSet.Clear();
            this.booksTableAdapter.FillBy(this.bookDataSet.books, s);
        }

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            try
            {
                pd.Print();
            }
            catch (InvalidPrinterException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            PaintEventArgs myPaintArgs = new PaintEventArgs(e.Graphics, new Rectangle(new Point(0, 0), this.Size));
            this.InvokePaint(booksDataGridView, myPaintArgs);
            /*float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = .MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;
            String line = null;

            // Calculate the number of lines per page.
            linesPerPage = ev.MarginBounds.Height /
               printFont.GetHeight(ev.Graphics);

            // Iterate over the file, printing each line.
            while (count < linesPerPage &&
               ((line = streamToPrint.ReadLine()) != null))
            {
                yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(line, printFont, Brushes.Black,
                   leftMargin, yPos, new StringFormat());
                count++;
            }

            // If more lines exist, print another page.
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;*/

        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {

        }

        private void booksNavigator1_HelpRequested(object sender, HelpEventArgs hlpevent)
        {
            Debugger.Break();
        }

        private void booksDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            this.booksDataGridView.Rows[e.RowIndex].ErrorText = "";

            if (this.booksDataGridView.Rows[e.RowIndex].IsNewRow) { return; }
            if (e.FormattedValue.ToString() == "")
            {
                e.Cancel = true;
                this.booksDataGridView.Rows[e.RowIndex].ErrorText = "The value must not be empty or null.";
            }

        }

        private void booksDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            DataGridViewRow row = this.booksDataGridView.Rows[e.RowIndex];
            if (this.booksDataGridView.Rows[e.RowIndex].IsNewRow) { return; }
            //DataGridViewCell column_author = row.Cells[this.booksDataGridView.Columns["author"].Index];
            DataGridViewCell column_author = row.Cells[0]; //author cell
            DataGridViewCell column_title = row.Cells[1]; //title cell
            DataGridViewCell column_keywords = row.Cells[2]; //keyword cell
            if (column_author.FormattedValue.ToString() == "")
            {
                e.Cancel = true;
            }
            else if (column_title.FormattedValue.ToString() == "")
            {  
                e.Cancel = true;
            }
            else if (column_keywords.FormattedValue.ToString() == "")
            {
                e.Cancel = true;
            }
        }

        private void booksDataGridView_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = this.booksDataGridView.Rows[e.RowIndex];
            DataGridViewCell cell = row.Cells[e.ColumnIndex];
        }
    }
}
